package com.wty.cmims.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.wty.cmims.service.ImageUploadService;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class ImageUploadServiceImpl implements ImageUploadService {
    @Override
    public String upload(InputStream in, String filename) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取RAM用户的访问密钥（AccessKey ID和AccessKey Secret）。
        String accessKeyId = "LTAI5tCyViSXHjdRXtfUGjNL";
        String accessKeySecret = "N6cVFG0dlYcJ5QkRmmaDITdU8xS5rG";
        // 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "tearyarnbucket";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "imgs/" + filename;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        try {
            ossClient.putObject(bucketName, objectName, in);
        } catch (OSSException | ClientException oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "https://tearyarnbucket.oss-cn-beijing.aliyuncs.com/" + objectName;
    }
}